<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24">
        <span>选择用户：</span>
        <el-select v-model="selectedUser" placeholder="用户" @change="handleUserChange" style="width: 90%;">
          <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id"></el-option>
        </el-select>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <span>选择用户角色：</span>
        <el-transfer
            v-model="selectedRolesKeys"
            :data="rolesOptions"
            :props="{ key: 'id', label: 'name' }"
            :titles="['角色列表', '已选择角色']"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入角色名"
            style="width: 100%;">
        </el-transfer>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-button type="primary" @click="submitUserRole">确认</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {selectRole, selectRoleById, selectUser} from "@/http/home/user/get";
import {updateUserRoles} from "@/http/home/user/post";

export default {
  data() {
    return {
      selectedUser: null, // 当前选中的用户
      selectedRolesKeys: [], // 选中的角色的keys
      users: [], // 所有用户
      rolesOptions: [], // 角色选项，用于穿梭框显示
    };
  },
  mounted() {
    this.fetchUsers();
    this.fetchRoles();
  },
  methods: {
    async fetchUsers() {
      const res = await selectUser(null, 1, 1000);
      this.users = res.data.data.records;
    },
    async fetchRoles() {
      const res = await selectRole();
      this.rolesOptions = res.data.data.map(role => ({
        id: role.value,
        name: role.label,
      }));
    },
    handleUserChange(value) {
      this.getUserRoles(value);
    },
    async getUserRoles(userId) {
      const res = await selectRoleById(userId);
      if (res.data.code == 200) {
        // Map selected roles to the keys used by el-transfer
        this.selectedRolesKeys = res.data.data.map(item => String(item.roleId));
      }
    },
    filterMethod(query, item) {
      return item.name.indexOf(query) > -1;
    },
    async submitUserRole() {
      const payload = {
        userId: this.selectedUser,
        roleIds: this.selectedRolesKeys,
      };

      if (!this.selectedUser || !this.selectedRolesKeys.length) {
        this.$message.error('请确保选择了用户和至少一个角色');
        return; // 提前返回，不执行后续代码
      }

      try {
        const res = await updateUserRoles(payload);
        if (res.data.code === 200) {
          this.$message.success('用户角色更新成功');
        } else {
          this.$message.error('用户角色更新失败');
        }
      } catch (error) {
        console.error('更新用户角色出错:', error);
        this.$message.error('更新用户角色出错');
      }
    },
  },
};
</script>